var bytenode = require("bytenode");
var fs = require("fs");
var path = require("path");

fs.exists("./dist", (exist) => {
  if (exist) {
    delDir("./dist");
  }
  fs.mkdirSync("./dist");
});

// 拷贝目录到 dist 下
fs.readdir("./", (err, files) => {
  if (err) {
    console.error(err);
    return;
  }
  for (var i = 0; i < files.length; i++) {
    if ([".git", "node_modules"].includes(files[i])) {
      continue;
    }
    var stat = fs.statSync("./" + files[i]);
    if (stat.isFile()) {
      if (files[i].indexOf("compile.js") == -1) {
        fs.writeFileSync(
          "./dist/" + files[i],
          fs.readFileSync("./" + files[i])
        );
      }
    } else if (stat.isDirectory() && files[i].indexOf("dist") == -1) {
      createDocs("./" + files[i], "./dist/" + files[i], function () {});
    } else {
    }
  }

  compileFile();
});

function compileFile() {
  compileDir("./dist/app");
}

const getStr = (text) => {
  let str = text;
  const DG = process.env.npm_lifecycle_script.match(/DG=(\d+)/g);
  const DG_HOST = process.env.npm_lifecycle_script.match(
    /DG_HOST=.*[^'"]/g
  );
  if (DG) {
    const s = DG[0].replace("DG=", "");
    str = str.replace("---DG---", s);
  }
  if (DG_HOST) {
    const s = DG_HOST[0].replace("DG_HOST=", "");
    str = str.replace("---DONGLE_HOST---", s);
  }
  return str;
};

function compileDir(dir) {
  var stat = fs.statSync(dir);
  if (stat.isFile() && path.extname(dir) === ".js") {
    // 文件，直接转换
    if (dir.indexOf("/dongle/index.js") > -1) {
      const str = fs.readFileSync(dir, "utf-8");
      const code = getStr(str);
      fs.writeFileSync(dir, code);
      console.log('code--', code)
      bytenode.compileFile({
        filename: dir,
      });
    } else {
      bytenode.compileFile({
        filename: dir,
      });
    }
    fs.unlinkSync(dir);
  } else if (stat.isDirectory()) {
    // 目录，列出文件列表，循环处理
    var files = fs.readdirSync(dir);
    for (var i = 0; i < files.length; i++) {
      if (["config.js"].includes(files[i])) {
        continue;
      }
      var file = dir + "/" + files[i];
      console.log(file, 'file')
      compileDir(file);
    }
  } else {
  }
}

//递归创建目录 同步方法
function mkdirsSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

function _copy(src, dist) {
  var paths = fs.readdirSync(src);
  paths.forEach(function (p) {
    var _src = src + "/" + p;
    var _dist = dist + "/" + p;
    var stat = fs.statSync(_src);
    if (stat.isFile()) {
      // 判断是文件还是目录
      fs.writeFileSync(_dist, fs.readFileSync(_src));
    } else if (stat.isDirectory()) {
      copyDir(_src, _dist); // 当是目录是，递归复制
    }
  });
}

/*
 * 复制目录、子目录，及其中的文件
 * @param src {String} 要复制的目录
 * @param dist {String} 复制到目标目录
 */
function copyDir(src, dist) {
  var b = fs.existsSync(dist);
  // console.log("dist = " + dist);
  if (!b) {
    // console.log("mk dist = ", dist);
    mkdirsSync(dist); //创建目录
  }
  console.log("_copy start");
  _copy(src, dist);
}

function createDocs(src, dist, callback) {
  copyDir(src, dist);
  if (callback) {
    callback();
  }
}

function delDir(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach((file, index) => {
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath); //递归删除文件夹
      } else {
        fs.unlinkSync(curPath); //删除文件
      }
    });
    console.log(path)
    fs.rmdirSync(path);
  }
}
